import base64 from './base64'
/**
 * @description 操作微信小程序的本地缓存
 * @author zhiyuan Liang
 * @since 2018/05/02
 */
const storage = {
  /**
   * @description 从本地缓存中同步获取指定key对应的内容
   * @param {String} key key
   */
  get(key) {
    try {
      var decoder = wx.getStorageSync(key)
      if (decoder) {
        let json = decoder

        json = base64.decode(decoder)

        return JSON.parse(json)
      }
      return null
    } catch (e) {
      return null
    }
  },
  /**
   * @description 将data存储在本地缓存中指定的key中,会覆盖掉原来该key对应的内容,这是一个同步接口
   * @param {String} key key
   * @param {String} value value
   */
  save(key, value) {
    if (value == null) {
      storage.remove(key)
      return
    }
    let json = JSON.stringify(value)
    let decoder = json

    decoder = base64.encode(json)

    try {
      wx.setStorageSync(key, decoder)
    } catch (e) {
      // Do something when catch error
    }
  },
  /**
   * @description 从本地缓存中同步移除指定key
   * @param {String} key key
   */
  remove(key) {
    try {
      wx.removeStorageSync(key)
    } catch (e) {
      // Do something when catch error
    }
  },
  /**
   * @description 同步清理本地数据缓存
   */
  clear() {
    try {
      wx.clearStorageSync()
    } catch (e) {
      // Do something when catch error
    }
  }
}

export default storage
